/*
 * Package il.ac.biu.cs.grossmm.test.test1
 * File Notifier.java
 * 
 * This is a part of presence service framework API. 
 * See javadoc for more information.
 *  
 * Copyright (C) 2006 Grossmann Mark
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package il.ac.biu.cs.grossmm.tests.test2;

import static il.ac.biu.cs.grossmm.api.data.NodeTypeByInterface.*;
import static il.ac.biu.cs.grossmm.api.keys.PatternFactory.*;
import static il.ac.biu.cs.grossmm.api.presence.BaseVocabulary.*;
import static il.ac.biu.cs.grossmm.api.presence.ResourceType.*;
import il.ac.biu.cs.grossmm.api.OperationFailedException;
import il.ac.biu.cs.grossmm.api.data.Root;
import il.ac.biu.cs.grossmm.api.flow.ActiveDataManager;
import il.ac.biu.cs.grossmm.api.flow.NodeManipulator;
import il.ac.biu.cs.grossmm.api.flow.NotificationPoint;
import il.ac.biu.cs.grossmm.api.flow.Track;
import il.ac.biu.cs.grossmm.api.keys.Key;
import il.ac.biu.cs.grossmm.api.presence.Pidf;
import il.ac.biu.cs.grossmm.api.server.Component;
import il.ac.biu.cs.grossmm.api.server.ComponentManager;
import il.ac.biu.cs.grossmm.api.server.ServiceManager;
import il.ac.biu.cs.grossmm.api.server.Service;

import java.util.ArrayList;
import java.util.Random;
import java.util.logging.Logger;

public class Notifier extends Thread implements
	il.ac.biu.cs.grossmm.api.flow.Notifier<Pidf>, Component, Service {

	ActiveDataManager adm;

	private NotificationPoint<Pidf> np;

	private Logger logger = Logger.getLogger("Notifier");

	private ServiceManager serviceManager;

	private ComponentManager container;

	private volatile ArrayList<Key> keys = new ArrayList<Key>();

	private boolean up;

	public void fetch(Key key, Track track, Root node,
		NodeManipulator manipulator)
	{
		// TODO Implement fetch
		// 
		throw new RuntimeException("Not implemented");
	}

	public boolean subscribe(Key key, Track track) throws Exception
	{
		try {
			// logger.info("Subscribed "+key);
			Root<Pidf> r = np.activated(key);
			NodeManipulator man = np.writeLock(r);
			man.setValue(r, Pidf.ENTITY, "alice");
			np.writeUnlock(r);
			
			synchronized(keys) {
				keys.add(key);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}

		return true;
	}

	public void unsubscribe(Key key)
	{
		logger.info("Unsubscribed " + key);
	}

	public void setComponentManager(ComponentManager container)
		throws Exception
	{
		this.container = container;
		adm = container.getByClass(ActiveDataManager.class);

		np =
			adm.createNotificationPoint(this, pattern(String.class, mandatory(
				RESOURCE_TYPE, PRESENCE)), nodeType(Pidf.class), 1.0);
	}

	public void aborted(Object hint, Exception e) throws Exception
	{
		throw e;
	}

	public void start(ServiceManager serviceManager) throws Exception
	{
		this.serviceManager = serviceManager;
		logger.info("Started");
		up = true;
		start();
	}

	public void stop(Exception exception)
	{
		up = false;
		try {
			synchronized(this) {
				wait();
			}
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		logger.info("Stopped");
	}

	public void terminated(Object serviceHint, Exception e) throws Exception
	{
		throw e;
	}

	@Override
	public void run()
	{
		try {
			sleep(4000);
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		Random r = new Random();
		
		int count = 0;
		long t = System.currentTimeMillis();
		
		
		while( up ) {
//			try {
//				sleep(10);
//			} catch (InterruptedException e1) {
//				// TODO Auto-generated catch block
//				e1.printStackTrace();
//			}
			
			Key key ;
			int size, i, j;
			synchronized(keys) {
			size = keys.size();
			if( size == 0 )
				continue; 
			i = r.nextInt(size);
			j = r.nextInt();
			
			key = keys.get(i);
			}
			
			Root<Pidf> root = np.getRoot(key);
			NodeManipulator man = np.writeLock(root);
			
			try {
				man.setValue(root, Pidf.ENTITY, "alice"+j);
			} catch (OperationFailedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			np.writeUnlock(root);
			
			count++;
			
			if( count == 200000 ) {
				long t1 = System.currentTimeMillis();
				System.out.println("TIME: "+(t1-t));
				t=t1;
				count = 0;
			}
		}
		
		synchronized(this) {
			notify();
		}
	}
}
